﻿
var isFirstLoad = true;
$(document).ready(function () {


    HienThiGiaoDien(1);

    $('#HuyPhong').click(function () {
        alert('huy phong');
        var idphong = $('#IDPhongDangDanh').attr('value');
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 23,
            UserName: username,
            Id: id,
            IdPhong: idphong
        }));

        HienThiGiaoDien(1);
    });

    $('#TaoPhong').click(function () {
        var nPhong = $('.phong').length;
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 22,
            UserName: username,
            Id: id,
            IdPhong: nPhong
        }));
    });

    $('#RoiKhoiPhong').click(function () {
        alert('Rời phòng!');
        roiPhong();
        HienThiGiaoDien(1);
    });

    $('#MoiRaKhoiPhong').click(function () {
        var idphong = $('#IDPhongDangDanh').attr('value');
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 21,
            UserName: username,
            Id: id,
            IdPhong: idphong
        }));

        $('#TenDoiThu').text("");
        $('#BatDauTranDau').hide();
        $('#MoiRaKhoiPhong').hide();
        $('#ChoChuPhongBatDau').hide();
        $('#RoiKhoiPhong').hide();
        //$('#IDPhongDangDanh').attr('value', idphong)
        HienThiGiaoDien(2);
    });

    $('.ChatFormItem form').ajaxForm({
        target: '#preview',
        success: function () {
        }
    });

    $('#formgamechat').ajaxForm({
        target: '#preview',
        success: function () {
        }
    });

    $('#logout').live('click', function () {
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 8,
            UserName: username,
            Id: id
        }));
        ws.onclose();
        ws.close();
    });

    $('#BatDauTranDau').live('click', function () {

        var idphong = $('#IDPhongDangDanh').attr('value');
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 17,
            UserName: username,
            Id: id,
            IdPhong: idphong
        }));

    });

    $('.frienditem').live('click', function () {
        var username = $(this).text();
        var id = $(this).find('#frienditem_id').attr('value');
        addNewChatForm(username, id);
    });


    $('.phong').live('click', function () {
        var idphong = $(this).find('#phong_id').attr('value');
        var songuoihien = $(this).find('#phong_songuoi').attr('value');
        if (songuoihien == 0) {
            $(('#phong_ghe_left_' + idphong)).attr('src', '../../Content/Images/ghe_trai_dachon.png');
            $(this).find('#phong_songuoi').attr('value', '1');
            $('#BatDauTranDau').hide();
            $('#MoiRaKhoiPhong').hide();
            $('#ChoChuPhongBatDau').hide();
            $('#RoiKhoiPhong').hide();
            $('#IDPhongDangDanh').attr('value', idphong)
            HienThiGiaoDien(2);

            var username = $('#TK_UserName').attr('value');
            var id = $('#TK_Id').attr('value');
            ws.send(window.JSON.stringify({
                Type: 12,
                UserName: username,
                Id: id,
                IdPhong: idphong,
                SoNguoi: 1
            }));
        }
        else if (songuoihien == 1) {
            //Cập nhật số người, và màu sắc của ghế
            $(('#phong_ghe_phai_' + idphong)).attr('src', '../../Content/Images/ghe_phai_dachon.png');
            $(this).find('#phong_songuoi').attr('value', '2');

            var username = $('#TK_UserName').attr('value');
            var id = $('#TK_Id').attr('value');
            ws.send(window.JSON.stringify({
                Type: 12,
                UserName: username,
                Id: id,
                IdPhong: idphong,
                SoNguoi: 2
            }));

            $('#IDPhongDangDanh').attr('value', idphong)

        }
        else if (songuoihien == 2) {
            alert("Phòng đã đủ số người !");
        }

    });


    window.onload = start;

    window.onbeforeunload = function () {
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 8,
            UserName: username,
            Id: id
        }));
        ws.onclose();
        ws.close();
    };
});

function encode(data) {
    var str = String.fromCharCode.apply(null, data);
    return btoa(str).replace(/.{76}(?=.)/g, '$&\n');
}


function UploadImage_Complete() {
    if (isFirstLoad == true) {
        isFirstLoad = false;
        return;
    }
    document.getElementById("ImgForm").reset();
    var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);
    if (newImg.IsValid == false) {
        alert("Cập nhật không thành công !");
    }
    else {
        alert("Cập nhật thành công !");
    }

    $('#HoTen').val("");
    $('#NgaySinh').text("");
    $('#NhapLaiMatKhau').val("");
    $('#MatKhau').text("");
    $('#DienThoai').text("");
    $('#DiaChi').text("");
    $('#HinhAnh').text("");    

}

function roiPhong()
{
    var idphong = $('#IDPhongDangDanh').attr('value');
    var username = $('#TK_UserName').attr('value');
    var id = $('#TK_Id').attr('value');
    ws.send(window.JSON.stringify({
        Type: 13,
        UserName: username,
        Id: id,
        IdPhong: idphong
    }));
}

function addPhong(idphong, songuoi) {
    var newItem = "<div id='phong_" + idphong + "' class='phong'>" +
                                    "<input type='hidden' id='phong_id' value='" + idphong + "' />" +
                                    "<input type='hidden' id='phong_songuoi' value='" + songuoi + "' />" +
                                    "<div style='text-align: center'>Phòng: " + idphong + "</div>" +
                                    "<div id='cuoc'>";

    if (songuoi == 0) {
        newItem += "<div id='nguoi_1Left' class='gheleft'>" +
             "<img id='phong_ghe_left_" + idphong + "' src='../../Content/Images/ghe_trai_chuachon.png' width='25' height='25' />" +
         "</div>" +
         "<div id='ban_1' style='text-align: center'>" +
             "<img src='../../Content/Images/ban_co_vua.png' style='float:left' width='70' height='70' /></div>" +
         "<div id='nguoi_1Right' class='gheright'>" +
             "<img id='phong_ghe_phai_" + idphong + "' src='../../Content/Images/ghe_phai_chuachon.png' width='25' height='25' />" +
         "</div>";
    }
    else if (songuoi == 1) {
        newItem += "<div id='nguoi_1Left' class='gheleft'>" +
             "<img id='phong_ghe_left_" + idphong + "' src='../../Content/Images/ghe_trai_dachon.png' width='25' height='25' />" +
         "</div>" +
         "<div id='ban_1' style='text-align: center'>" +
             "<img src='../../Content/Images/ban_co_vua.png' style='float:left' width='70' height='70' /></div>" +
         "<div id='nguoi_1Right' class='gheright'>" +
             "<img id='phong_ghe_phai_" + idphong + "' src='../../Content/Images/ghe_phai_chuachon.png' width='25' height='25' />" +
         "</div>";
    }
    else if (songuoi == 2) {
        newItem += "<div id='nguoi_1Left' class='gheleft'>" +
             "<img id='phong_ghe_left_" + idphong + "' src='../../Content/Images/ghe_trai_dachon.png' width='25' height='25' />" +
         "</div>" +
         "<div id='ban_1' style='text-align: center'>" +
             "<img src='../../Content/Images/ban_co_vua.png' style='float:left' width='70' height='70' /></div>" +
         "<div id='nguoi_1Right' class='gheright'>" +
             "<img id='phong_ghe_phai_" + idphong + "' src='../../Content/Images/ghe_phai_dachon.png' width='25' height='25' />" +
         "</div>";
    }

    newItem += "</div>" + "</div>";
    $('#DanhSachPhong').append(newItem);

}

function addNewChatForm(username, id) {
    var check = document.getElementById('formchat' + id);
    if (check == null) {
        var newitem = "<div class='ChatFormItem'>" +
                      "<form id='formchat" + id + "' onsubmit='sendChatMessage(this)'>" +
                      "<table width='100%' border='0' cellspacing='0' cellpadding='0'> " +
                      "<tr> " +
                      "<td class='TitleChatForm'>" + username + "</td> " +
                      "</tr> " +
                      "<tr> " +
                      "<td style='height: 160px;'> " +
                                    "<div id='ChatLineContainerScroller" + id + "' class='ChatLineContainerScroller'>" +
                                        "<div id='ChatLineContain" + id + "'> " +
                                        "</div> " +
                                    "</div> " +
                                "</td> " +
                            "</tr> " +
                            "<tr> " +
                                "<td style='height: 25px'> " +
                                "<input style='height: 25px; width: 140px;' name='ChatContain' type='text' id='MyButton' /> " +
                                "<input id='buttonEnter' type='image' src='../../Content/Images/enter.png' />" +
                                "<input type='hidden' id='FriendId' value='" + id + "' /> " +
                                "<input type='hidden' id='FriendUserName' value='" + username + "' /> " +
                                "</td> " +
                            "</tr> " +
                        "</table> " +
                    "</form> " +
                    "</div>";

        $('#ChatFormContainer').append(newitem);

        $('.ChatFormItem form').ajaxForm({
            target: '#preview',
            success: function () {
            }
        });

    }
}

function sendGameChatMessage(Object) {

    var contain = Object.ChatContain.value;
    var fromID = $('#TK_Id').attr('value');
    var fromUserName = $('#TK_UserName').attr('value');

    var newlineitem = document.createElement('div');

    //Cap nhat giao dien user gui.
    newlineitem.className = "chatline";
    newlineitem.innerHTML = "<span style='font-weight: bold; color: #800080'>" + fromUserName + "</span> :" + contain;
    document.getElementById('chatcontent').appendChild(newlineitem);
    Object.ChatContain.value = "";
    var idphong = $('#IDPhongDangDanh').attr('value');

    ws.send(window.JSON.stringify({
        Type: 18,
        UserName: fromUserName,
        Id: fromID,
        IdPhong: idphong,
        Contain: contain
    }));
}

function sendChatMessage(Object) {

    var contain = Object.ChatContain.value;
    var fromID = $('#TK_Id').attr('value');
    var fromUserName = $('#TK_UserName').attr('value');
    var toID = Object.FriendId.value;
    var toUserName = Object.FriendUserName.value;
    var newlineitem = document.createElement('div');

    //Cap nhat giao dien user gui.
    newlineitem.className = "ChatLineItem";
    newlineitem.innerHTML = "<span style='font-weight: bold; color: #800080'>" + fromUserName + "</span> :" + contain;
    document.getElementById(('ChatLineContain' + toID)).appendChild(newlineitem);
    Object.ChatContain.value = "";

    //Gui doan chat len server.
    ws.send(window.JSON.stringify({
        Type: 1,
        UserName: fromUserName,
        Id: fromID,
        ToUser: toUserName,
        ToID: toID,
        Contain: contain
    }));
}

var start = function SocketThread() {
    var inc = document.getElementById('incomming');
    var wsImpl = window.WebSocket || window.MozWebSocket;
    // create a new websocket and connect
    window.ws = new wsImpl('ws://localhost:8181', 'my-protocol');
    // when data is comming from the server, this metod is called
    ws.onmessage = function (message) {
        var data = window.JSON.parse(message.data);
        //Register: 0
        //Chat:     1
        //Server:   2
        //Broadcast:3
        //Leave:    4
        //SendListFriend: 5
        switch (data.Type) {
            case 0:
                {
                    break;
                }
            case 1:
                {
                    var id = data.Id;
                    var contain = data.Contain;
                    var username = data.UserName;
                    //Kiem tra cua form chat da duoc tao chua, neu khong thi tao.
                    var check = document.getElementById('formchat' + id);
                    if (check == null) {
                        addNewChatForm(username, id);
                        $('.ChatFormItem form').ajaxForm({
                            target: '#preview',
                            success: function () {
                            }
                        });
                    }

                    //Them chat line 
                    var newlineitem = document.createElement('div');
                    newlineitem.className = "ChatLineItem";
                    newlineitem.innerHTML = "<span style='font-weight: bold; color: #800080'>" + username + "</span> :" + contain;
                    document.getElementById(('ChatLineContain' + id)).appendChild(newlineitem);
                    break;
                }
            case 2:
                {
                    break;
                }
            case 5:
                {
                    var len = data.ListFriend.length;
                    for (var i = 0; i < len; i++) {
                        //Tao danh sách bạn ở đây
                        var newItem = "<div class='frienditem' id='frienditem" + data.ListFriend[i].Id + "'> ";
                        if (data.ListFriend[i].HinhAnh == null) {
                            newItem += "<div id='avatarimage'> <img src='../../Content/Images/noavatar.png' width='38' height='38' /> </div>";
                        }
                        else {
                            newItem += "<div id='avatarimage'> <img src='data:image/gif;base64," + encode(data.ListFriend[i].HinhAnh) + "' width='38' height='38' /> </div>";
                        }
                        newItem += "<div id='username'>" + data.ListFriend[i].UserName + "</div>" +
                                        "<div id='statusimage'>";

                        if (data.ListFriend[i].IsOnline == true) {
                            newItem += "<img id='avatar" + data.ListFriend[i].Id + "' src='../../Content/Images/online.png' width='35' height='34' />";
                        }
                        else {
                            newItem += "<img id='avatar" + data.ListFriend[i].Id + "' src='../../Content/Images/offline.png' width='35' height='34' />";
                        }

                        newItem += "</div>" +
                                        "<input type='hidden' id='frienditem_id' value='" + data.ListFriend[i].Id + "' />" +
                                    "</div>";
                        $('#listFriend').append(newItem);
                    }

                    //Khởi tạo danh dách phòng.
                    var lenPhong = data.ListPhong.length;
                    for (var i = 0; i < lenPhong; i++) {
                        addPhong(data.ListPhong[i].IdPhong, data.ListPhong[i].SoNguoi);
                    }

                    break;
                }
            case 7: //Online
                {
                    var IdOnLine = data.Id;
                    $(('#avatar' + IdOnLine)).attr('src', '../../Content/Images/online.png');
                    break;
                }
            case 8: //Offline
                {
                    var IdOffLine = data.Id;
                    $(('#avatar' + IdOffLine)).attr('src', '../../Content/Images/offline.png');
                    break;
                }
            case 10: //ResultAddFriend
                {
                    if (data.Result == false) {
                        alert('Thêm bạn không thành công!');
                    }
                    else {
                        var newItem = "<div class='frienditem'  id='frienditem" + data.NewFriend.Id + "'> ";
                        if (data.NewFriend.HinhAnh == null) {
                            newItem += "<div id='avatarimage'> <img src='../../Content/Images/noavatar.png' width='38' height='38' /> </div>";
                        }
                        else {
                            newItem += "<div id='avatarimage'> <img src='data:image/gif;base64," + encode(data.NewFriend.HinhAnh) + "' width='38' height='38' /> </div>";
                        }
                        newItem += "<div id='username'>" + data.NewFriend.UserName + "</div>" +
                                        "<div id='statusimage'>";

                        if (data.NewFriend.IsOnline == true) {
                            newItem += "<img id='avatar" + data.NewFriend.Id + "' src='../../Content/Images/online.png' width='35' height='34' />";
                        }
                        else {
                            newItem += "<img id='avatar" + data.NewFriend.Id + "' src='../../Content/Images/offline.png' width='35' height='34' />";
                        }

                        newItem += "</div>" +
                                        "<input type='hidden' id='frienditem_id' value='" + data.NewFriend.Id + "' />" +
                                    "</div>";

                        $('#listFriend').append(newItem);
                    }
                    break;
                }
            case 11:
                {
                    $('#frienditem' + data.Id).remove();
                    break;
                }
            case 14:
                {
                    var IdPhong = data.IdPhong;
                    var SoNguoi = data.SoNguoi;
                    if (SoNguoi == 1) {
                        $(('#phong_ghe_left_' + IdPhong)).attr('src', '../../Content/Images/ghe_trai_dachon.png');
                        $(('#phong_ghe_phai_' + IdPhong)).attr('src', '../../Content/Images/ghe_phai_chuachon.png');
                        $(('#phong_' + IdPhong)).find('#phong_songuoi').attr('value', '1');
                    }
                    else if (SoNguoi == 2) {
                        $(('#phong_ghe_left_' + IdPhong)).attr('src', '../../Content/Images/ghe_trai_dachon.png');
                        $(('#phong_ghe_phai_' + IdPhong)).attr('src', '../../Content/Images/ghe_phai_dachon.png');
                        $(('#phong_' + IdPhong)).find('#phong_songuoi').attr('value', '2');
                    } else if (SoNguoi == 0) {
                        $(('#phong_ghe_left_' + IdPhong)).attr('src', '../../Content/Images/ghe_trai_chuachon.png');
                        $(('#phong_ghe_phai_' + IdPhong)).attr('src', '../../Content/Images/ghe_phai_chuachon.png');
                        $(('#phong_' + IdPhong)).find('#phong_songuoi').attr('value', '0');
                    }
                    break;
                }
            case 15:  //Update giao diện người chơi 1 sau khi có người 2 vào phòng.
                {
                    $('#BatDauTranDau').show();
                    $('#MoiRaKhoiPhong').show();
                    $('#ChoChuPhongBatDau').hide();
                    $('#RoiKhoiPhong').hide();
                    $('#ChoDoiThu').hide();
                    $('#TenDoiThu').text(data.UserName);
                    break;
                }
            case 16:  //Update giao diện người chơi 2 sau khi vào phòng.
                {
                    $('#ChoChuPhongBatDau').show();
                    $('#HuyPhong').hide();
                    $('#BatDauTranDau').hide();
                    $('#MoiRaKhoiPhong').hide();
                    $('#RoiKhoiPhong').show();
                    $('#ChoDoiThu').hide();
                    $('#TenDoiThu').text(data.UserName);
                    HienThiGiaoDien(2);
                    break;
                }
            case 17: //Bắt đầu trận đấu.
                {
                    HienThiGiaoDien(3);
                    if (data.ThuTuDi == 1) {
                        alert("Ván cờ bắt đầu, bạn đi trước !");
                        currentPlayer = WHITE;
                        drawBoard();
                    }
                    else if (data.ThuTuDi == 2) {
                        alert("Ván cờ bắt đầu, bạn đi sau !");
                        currentPlayer = BLACK;
                        drawBoard();
                    }
                    break;
                }
            case 18: //Chat khi danh co
                {
                    var id = data.Id;
                    var contain = data.Contain;
                    var username = data.UserName;

                    var newlineitem = document.createElement('div');

                    //Cap nhat giao dien user gui.
                    newlineitem.className = "chatline";
                    newlineitem.innerHTML = "<span style='font-weight: bold; color: #800080'>" + username + "</span> :" + contain;
                    document.getElementById('chatcontent').appendChild(newlineitem);
                    Object.ChatContain.value = "";
                    var idphong = $('#IDPhongDangDanh').attr('value');

                    break;
                }

            case 19:
                {
                    var fromCell = data.FromCell;
                    var toCell = data.ToCell;
                    move(fromCell, toCell);
                    currentPlayer = WHITE;
                    drawBoard();
                    break;
                }
            case 20://win
                {
                    //thua rui 
                    alert('Thua nha cung!');
                    resetBoardData();
                    drawBoard();
                    $('#ChoChuPhongBatDau').show();
                    $('#HuyPhong').hide();
                    $('#BatDauTranDau').hide();
                    $('#MoiRaKhoiPhong').hide();
                    $('#RoiKhoiPhong').show();
                    $('#ChoDoiThu').hide();
                    HienThiGiaoDien(2);
                    break;
                }
            case 13://roi phong
                {
                    //$(this).find('#phong_songuoi').attr('value', '1');
                    if ($('#PhongCho').is(":visible"))//Nguoi choi dang o phong cho, nguoi choi 2 roi phong
                    {
                        $('#TenDoiThu').text("");
                        $('#BatDauTranDau').hide();
                        $('#MoiRaKhoiPhong').hide();
                        $('#ChoChuPhongBatDau').hide();
                        $('#HuyPhong').show();
                        $('#RoiKhoiPhong').hide();
                        //$('#IDPhongDangDanh').attr('value', idphong)
                        HienThiGiaoDien(2);
                    }
                    break;
                }
            case 21://bi kick ra khoi phong
                {
                    alert('Ban bi kick ra khoi phong!');
                    //roiPhong();
                    HienThiGiaoDien(1);
                    break;
                }
            case 22://them phong
                {
                    addPhong(data.IdPhong, 0);
                    break;
                }
            case 23://huy phong
                {
                    alert('Chu phong da roi phong!');
                    HienThiGiaoDien(1);
                    break;
                }
            case 24://invite result
                {
                    break;
                }
            case 25://invite request
                {
                    $('#invitor').text(data.fromUser);
                    $("#invite-request-form").dialog("open");
                    break;
                }
            case 26://Cung vao phong khi invite friend thanh cong
                {
                    var idphong = data.idPhong;
                    var songuoihien = data.SoNguoi;
                    if (songuoihien == 0) {
                        $(('#phong_ghe_left_' + idphong)).attr('src', '../../Content/Images/ghe_trai_dachon.png');
                        $(this).find('#phong_songuoi').attr('value', '1');
                        $('#BatDauTranDau').hide();
                        $('#MoiRaKhoiPhong').hide();
                        $('#ChoChuPhongBatDau').hide();
                        $('#RoiKhoiPhong').hide();
                        $('#IDPhongDangDanh').attr('value', idphong)
                        HienThiGiaoDien(2);

                        var username = $('#TK_UserName').attr('value');
                        var id = $('#TK_Id').attr('value');
                        ws.send(window.JSON.stringify({
                            Type: 12,
                            UserName: username,
                            Id: id,
                            IdPhong: idphong,
                            SoNguoi: 1
                        }));
                    }
                    else if (songuoihien == 1) {
                        //Cập nhật số người, và màu sắc của ghế
                        $(('#phong_ghe_phai_' + idphong)).attr('src', '../../Content/Images/ghe_phai_dachon.png');
                        $(this).find('#phong_songuoi').attr('value', '2');

                        var username = $('#TK_UserName').attr('value');
                        var id = $('#TK_Id').attr('value');
                        ws.send(window.JSON.stringify({
                            Type: 12,
                            UserName: username,
                            Id: id,
                            IdPhong: idphong,
                            SoNguoi: 2
                        }));

                        $('#IDPhongDangDanh').attr('value', idphong)

                    }
                    else if (songuoihien == 2) {
                        //alert("Phòng đã đủ số người !");
                    }
                }

        }
    };
    // when the connection is established, this method is called
    ws.onopen = function () {
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 0,
            UserName: username,
            Id: id
        }));
    };
    ws.onclose = function () {
        var username = $('#TK_UserName').attr('value');
        var id = $('#TK_Id').attr('value');
        ws.send(window.JSON.stringify({
            Type: 8,
            UserName: username,
            Id: id
        }));
    }
}

          
function HienThiGiaoDien(IdCuaSo) {
    if (IdCuaSo == 1) {
        $('#DanhSachPhong').show();
        $('#PhongCho').hide();
        $('#phong_danh_co').hide();

        //$('#MoiBan').show();
        //$('#TaoPhong').show();
    }
    else if (IdCuaSo == 2) {
        $('#DanhSachPhong').hide();
        $('#PhongCho').show();
        $('#phong_danh_co').hide();

        //$('#MoiBan').hide();
        //$('#TaoPhong').hide();
    }
    else if (IdCuaSo == 3) {
        $('#DanhSachPhong').hide();
        $('#PhongCho').hide();
        $('#phong_danh_co').show();

        //$('#MoiBan').hide();
        //$('#TaoPhong').hide();
    }
}


/////////////////////////////////////////////
$(function () {
    drawBoard();
});

var moveCount = 0;
var WHITE = 9999;
var BLACK = 6666;
var currentPlayer = WHITE;
var userColor = WHITE;//white 0 black


var WHITE_PAWN = 1;
var WHITE_KNIGHT = 2;
var WHITE_KING = 3;
var WHITE_BISHOP = 4;
var WHITE_ROOK = 5;
var WHITE_QUEEN = 6;

var BLACK_PAWN = -WHITE_PAWN;
var BLACK_KNIGHT = -WHITE_KNIGHT;
var BLACK_KING = -WHITE_KING;
var BLACK_BISHOP = -WHITE_BISHOP;
var BLACK_ROOK = -WHITE_ROOK;
var BLACK_QUEEN = -WHITE_QUEEN;

var board =
	[
		[BLACK_ROOK, BLACK_KNIGHT, BLACK_BISHOP, BLACK_KING, BLACK_QUEEN, BLACK_BISHOP, BLACK_KNIGHT, BLACK_ROOK],
		[BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN],
		[WHITE_ROOK, WHITE_KNIGHT, WHITE_BISHOP, WHITE_QUEEN, WHITE_KING, WHITE_BISHOP, WHITE_KNIGHT, WHITE_ROOK]
	];

var originalBoard =
	[
		[BLACK_ROOK, BLACK_KNIGHT, BLACK_BISHOP, BLACK_KING, BLACK_QUEEN, BLACK_BISHOP, BLACK_KNIGHT, BLACK_ROOK],
		[BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN, BLACK_PAWN],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[0, 0, 0, 0, 0, 0, 0, 0],
		[WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN, WHITE_PAWN],
		[WHITE_ROOK, WHITE_KNIGHT, WHITE_BISHOP, WHITE_QUEEN, WHITE_KING, WHITE_BISHOP, WHITE_KNIGHT, WHITE_ROOK]
	];

function resetBoardData() {
    for(var i=0; i<8; i++)
    {
        for (var j = 0; j < 8; j++)
        {
            board[i][j] = originalBoard[i][j];
        }
    }
}

function drawBoard() {
    var htmlStr = "";
    for (var i = 0; i < 8; i++) {
        for (var j = 0; j < 8; j++) {
            htmlStr += "<div class='cell " + ((i + j) % 2 == 0 ? "" : "dark") + "'>" + "<div class='" + getPieceName(board[i][j]) + "'" + "data='" + (i * 8 + j) + "'" + "></div>" + "</div>";

        }
    }
    $("#board").html(htmlStr);

    $(".cell div").filter(function () {
        return $(this).attr('class').indexOf(userColor ? 'WHITE' : 'BLACK') !== -1 && currentPlayer == userColor;
    }).draggable({ revert: 'invalid' });

    $(".cell div").droppable({
        drop: function (event, ui) {
            $(this)
            var from = ui.draggable.parent().find('div').attr('data');
            var to = parseInt($(this).attr('data'));
            var pieceName = $(this).attr('class').split(" ")[0];
            var validsCells = getValidCell(from);
            if (validsCells.indexOf(to) != -1) {
                move(from, to);
                currentPlayer = BLACK;
                var idphong = $('#IDPhongDangDanh').attr('value');
                var username = $('#TK_UserName').attr('value');
                var id = $('#TK_Id').attr('value');
                ws.send(window.JSON.stringify({
                    Type: 19,
                    UserName: username,
                    Id: id,
                    IdPhong: idphong,
                    FromCell: from,
                    ToCell: to
                }));
                if (checkWin()) {
                    //send to server toa win roi hehe :D 
                    alert("Tao win rui");
                    resetBoardData();
                    $('#BatDauTranDau').show();
                    $('#MoiRaKhoiPhong').show();
                    $('#ChoChuPhongBatDau').hide();
                    $('#HuyPhong').show();
                    $('#RoiKhoiPhong').hide();
                    $('#ChoDoiThu').hide();
                    HienThiGiaoDien(2);
                    ws.send(window.JSON.stringify({
                        Type: 20,
                        UserName: username,
                        Id: id,
                        IdPhong: idphong
                    }));
                }
            }
            drawBoard();
        }
    });

    $(".cell div").mousedown(function () {
        var from = parseInt($(this).attr('data'));
        var pieceName = $(this).attr('class').split(" ")[0];
        writeLog("from " + from + " name = " + pieceName);
        var validCells = getValidCell(from);
        removehightlightedCells();
        hightlightCells(validCells);
    });
}

function removehightlightedCells() {
    $("div[class*='hightlight']").removeClass("hightlight");
}

function hightlightCells(cells) {
    for (var i = 0; i < cells.length; i++) {
        var element = "div[data='" + cells[i] + "']";
        var e = $(element);
        $(element).parent().addClass("hightlight");
    }
}

function getValidCell(from) {
    var row = Math.floor(from / 8);
    var col = from % 8;
    var pieceName = getPieceName(board[row][col]);
    var validCells = new Array();
    if (pieceName.indexOf("KING") != -1) {
        validCells = getValidKingCellMove(row, col);
    } else if (pieceName.indexOf("QUEEN") != -1) {
        validCells = getValidQueenCellMove(row, col);
    } else if (pieceName.indexOf("BISHOP") != -1) {
        validCells = getValidBishopCellMove(row, col);
    } else if (pieceName.indexOf("KNIGHT") != -1) {
        validCells = getValidKnightCellMove(row, col);
    } else if (pieceName.indexOf("PAWN") != -1) {
        validCells = getValidPawnCellMove(row, col);
    } else if (pieceName.indexOf("ROOK") != -1) {
        validCells = getValidRookCellMove(row, col);
    }
    return validCells;
}

function getValidKnightCellMove(row, col) {
    var directionIndices = [[-2, -2, 2, 2, 1, -1, 1, -1],
							[-1, 1, -1, 1, -2, -2, 2, 2]];

    return getCellsWithDirectionIndicesNoStartArround(row, col, directionIndices)
}

function getValidPawnCellMove(row, col) {
    var directionIndices = [[-1, -1, -1], [-1, 1, 0]];

    if (isPawnFirstMove(row, col)) {
        directionIndices[0][directionIndices[0].length] = -2;
        directionIndices[1][directionIndices[1].length] = 0;
    }

    return getPawnCellsWithDirectionIndices(row, col, directionIndices);
}

function isPawnFirstMove(row, col) {
    if (row == 6)
        return true;
    return false;
}

function getValidQueenCellMove(row, col) {
    var rookCells = getValidRookCellMove(row, col);
    var bishopCells = getValidBishopCellMove(row, col);

    return mergeTwoArrays(rookCells, bishopCells);
}

function getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround) {
    var validCells = new Array();

    do {
        var newRow = -1;
        var newCol = -1;
        var removeDirectionIndices = new Array();
        for (var i = 0; i < directionIndices[0].length; i++) {
            newRow = row + directionIndices[0][i] * startSizeArround;
            newCol = col + directionIndices[1][i] * startSizeArround;

            if (!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)) {
                removeDirectionIndices[removeDirectionIndices.length] = i;
                continue;
            }

            validCells[validCells.length] = newRow * 8 + newCol;

            if (cellContainOpponentPiece(newRow, newCol)) {
                removeDirectionIndices[removeDirectionIndices.length] = i;
            }

        }

        for (var i = removeDirectionIndices.length - 1; i >= 0; i--) {
            directionIndices[0].splice(removeDirectionIndices[i], 1);
            directionIndices[1].splice(removeDirectionIndices[i], 1);
        }
        startSizeArround++;
    } while (directionIndices[0].length != 0);

    return validCells;
}

function getCellsWithDirectionIndicesNoStartArround(row, col, directionIndices) {
    var validCells = new Array();

    var newRow = -1;
    var newCol = -1;

    for (var i = 0; i < directionIndices[0].length; i++) {

        newRow = row + directionIndices[0][i];
        newCol = col + directionIndices[1][i];

        if (!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)) {
            continue;
        }

        validCells[validCells.length] = newRow * 8 + newCol;
    }

    return validCells;
}

function getPawnCellsWithDirectionIndices(row, col, directionIndices) {
    var validCells = new Array();

    var newRow = -1;
    var newCol = -1;

    for (var i = 0; i < directionIndices[0].length; i++) {
        // if(directionIndices[0][i] == 0 && directionIndices[1][i] == 0)
        // 	continue;

        newRow = row + directionIndices[0][i];
        newCol = col + directionIndices[1][i];

        if (!isValidCell(newRow, newCol) || cellContainOwnPiece(newRow, newCol)) {
            continue;
        }

        if (i == 0 || i == 1) {
            if (!cellContainOpponentPiece(newRow, newCol)) {
                continue;
            }
        }

        validCells[validCells.length] = newRow * 8 + newCol;
    }

    return validCells;
}

function getValidRookCellMove(row, col) {
    var validCells = new Array();
    var directionIndices = [[-1, 0, 1, 0], [0, 1, 0, -1]];

    var startSizeArround = 1;
    return getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround);
}

function getValidBishopCellMove(row, col) {
    var validCells = new Array();
    var directionIndices = [[-1, 1, 1, -1], [1, 1, -1, -1]];

    var startSizeArround = 1;
    return getCellsWithDirectionIndices(row, col, directionIndices, startSizeArround);
}

function cellContainOwnPiece(row, col) {
    if (board[row][col] > 0) {
        return true;
    }
    return false;
}

function isValidCell(row, col) {
    if (row >= 0 && row < 8)
        if (col >= 0 && col < 8)
            return true;

    return false;
}

function cellContainOpponentPiece(row, col) {
    if (board[row][col] < 0) {
        return true;
    }
    return false;
}

function getValidKingCellMove(row, col) {
    var directionIndices = [[-1, -1, 0, 1, 1, 1, 0, -1], [0, 1, 1, 1, 0, -1, -1, -1]];

    var validCells = new Array();

    for (var i = 0; i < directionIndices[0].length; i++) {
        var newRow = row + directionIndices[0][i];
        var newCol = col + directionIndices[1][i];
        if (isValidCell(newRow, newCol) && !cellContainOwnPiece(newRow, newCol)) {
            validCells[validCells.length] = newRow * 8 + newCol;
        }

    }

    return validCells;
}

function getPieceValue(pieceName) {
    if (pieceName == "WHITE_KING") {
        return WHITE_KING;
    } else if (pieceName == "WHITE_QUEEN") {
        return WHITE_QUEEN;
    } else if (pieceName == "WHITE_BISHOP") {
        return WHITE_BISHOP;
    } else if (pieceName == "WHITE_KNIGHT") {
        return WHITE_KNIGHT;
    } else if (pieceName == "WHITE_PAWN") {
        return WHITE_PAWN;
    } else if (pieceName == "WHITE_ROOK") {
        return WHITE_ROOK;
    } else if (pieceName == "BLACK_KING") {
        return BLACK_KING;
    } else if (pieceName == "BLACK_QUEEN") {
        return BLACK_QUEEN;
    } else if (pieceName == "BLACK_BISHOP") {
        return BLACK_BISHOP;
    } else if (pieceName == "BLACK_KNIGHT") {
        return BLACK_KNIGHT;
    } else if (pieceName == "BLACK_PAWN") {
        return BLACK_PAWN;
    } else if (pieceName == "BLACK_ROOK") {
        return BLACK_ROOK;
    }
    return 0;
}

function getPieceName(pieceValue) {
    switch (pieceValue) {
        case WHITE_KING: return 'WHITE_KING';
        case WHITE_QUEEN: return 'WHITE_QUEEN';
        case WHITE_ROOK: return 'WHITE_ROOK';
        case WHITE_BISHOP: return 'WHITE_BISHOP';
        case WHITE_KNIGHT: return 'WHITE_KNIGHT';
        case WHITE_PAWN: return 'WHITE_PAWN';

        case BLACK_KING: return 'BLACK_KING';
        case BLACK_QUEEN: return 'BLACK_QUEEN';
        case BLACK_ROOK: return 'BLACK_ROOK';
        case BLACK_BISHOP: return 'BLACK_BISHOP';
        case BLACK_KNIGHT: return 'BLACK_KNIGHT';
        case BLACK_PAWN: return 'BLACK_PAWN';

        default: return 'EMPTY';
    }
}

function move(from, to) {
    var iFrom = Math.floor(from / 8);
    var jFrom = from % 8;
    var iTo = Math.floor(to / 8);
    var jTo = to % 8;
    board[iTo][jTo] = board[iFrom][jFrom];
    board[iFrom][jFrom] = 0;
}

function checkWin() {
    for (var i = 0; i < board.length; i++) {
        for (var j = 0; j < board[0].length; j++) {
            if (board[i][j] == BLACK_KING) {
                return false;
            }
        }
    }
    return true;
}

//Hàm thêm xóa bạn 
$(function () {
    var name = $("#name"),
        allFields = $([]).add(name);
    function updateTips(t) {
        tips
            .text(t)
            .addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    var namecancel = $("#namecancel"),
      allFields = $([]).add(namecancel);
    function updateTips(t) {
        tips
            .text(t)
            .addClass("ui-state-highlight");
        setTimeout(function () {
            tips.removeClass("ui-state-highlight", 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {
        if (o.val().length > max || o.val().length < min) {
            o.addClass("ui-state-error");
            updateTips("Length of " + n + " must be between " +
                min + " and " + max + ".");
            return false;
        } else {
            return true;
        }
    }

    function checkRegexp(o, regexp, n) {
        if (!(regexp.test(o.val()))) {
            o.addClass("ui-state-error");
            updateTips(n);
            return false;
        } else {
            return true;
        }
    }

    $("#dialog-form").dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Add friend": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");
                bValid = bValid && checkLength(name, "username", 3, 16);
                if (bValid) {
                    //Thêm moi ban o day.
                    var username = $('#TK_UserName').attr('value');
                    var id = $('#TK_Id').attr('value');
                    ws.send(window.JSON.stringify({
                        Type: 9,
                        UserName: username,
                        Id: id,
                        ToUser:name.val()
                    }));
                    $(this).dialog("close");
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });


    $("#exitdialog-form").dialog({
        autoOpen: false,
        height: 250,
        width: 350,
        modal: true,
        buttons: {
            "Delete friend": function () {
                var bValid = true;
                allFields.removeClass("ui-state-error");
                bValid = bValid && checkLength(namecancel,"username", 3, 16);
                if (bValid) {
                    var username = $('#TK_UserName').attr('value');
                    var id = $('#TK_Id').attr('value');
                    ws.send(window.JSON.stringify({
                        Type: 11,
                        UserName: username,
                        Id: id,
                        ToUser: namecancel.val()
                    }));
                    $(this).dialog("close");
                }
                else {
                    alert('NULL');
                }
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        },
        close: function () {
            allFields.val("").removeClass("ui-state-error");
        }
    });

    $("#AddFriendContainer")
        .click(function () {
            $("#dialog-form").dialog("open");
        });

    $("#DeleteFriend")
        .click(function () {
            $("#exitdialog-form").dialog("open");
        });
});